// pages/firstwrite/index.js
import Toast from '@vant/weapp/toast/toast';
const myRequest = require('../../utils/request.js'); // 导入整个模块
const app = getApp()
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'

import {
  writestore
} from '../../store/write/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dateshow: false,
    date: new Date().getTime(),
    maxDate: new Date().getTime(),
    minDate: new Date(1900, 1, 1).getTime(),
    datetime: '',
    person: '',
    money: '',
    num: 1,
    taglist:[],
    characteroption: [{
        text: '一个人',
        value: '一个人'
      },
      {
        text: '情侣/夫妻',
        value: '情侣/夫妻'
      },
      {
        text: '带孩子',
        value: '带孩子'
      },
      {
        text: '家庭出游',
        value: '家庭出游'
      },
      {
        text: '和朋友',
        value: '和朋友'
      },
      {
        text: '和同学',
        value: '和同学'
      },
      {
        text: '其他',
        value: '其他'
      },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //在onload中创建
   this.writeStrategyBindings = createStoreBindings(this, {
      store: writestore, // 确保这里传递的是正确的 store 对象
      fields: ['writestrategy'],
      actions: ['updatewritestrategy']
    });
    console.log(writestore.writestrategy);
    if(writestore.writestrategy.id){
      this.setData({
        datetime:writestore.writestrategy.date,
        person:writestore.writestrategy.people,
        money:writestore.writestrategy.money,
        num:writestore.writestrategy.num,
        taglist:writestore.writestrategy.tag,
      })
    }
  },
  addtag(){
    if(this.data.taglist.length==3){
      wx.showToast({
        title: '标签不能超过三个！',
        icon:'error'
      })
      return
    }
    let data=[...this.data.taglist]
    data.push('新标签')
    this.setData({
      taglist:data
    })
  },
  deleteTag(e) {
    const index = e.currentTarget.dataset.index;
    const taglist = this.data.taglist;
    taglist.splice(index, 1);
    this.setData({
      taglist: taglist
    });
  },
  tagchange(e) {
    const index = e.currentTarget.dataset.index; // 获取当前输入框的索引
    const value = e.detail.value; // 获取输入框的当前值

    // 手动限制输入的值不超过5个字符
    const newValue = value.length > 5 ? value.substring(0, 5) : value;

    // 更新 taglist 数组中对应项的值
    const taglist = this.data.taglist;
    if (index !== undefined) {
      taglist[index] = newValue;
      this.setData({
        taglist: taglist
      });
    }
  },
  showdate() {
    this.setData({
      dateshow: true
    })
  },
  //出发时间取消按钮
  closedata() {
    this.setData({
      dateshow: false
    })
  },


  //出发时间确定按钮
  updatedate() {
    this.setData({
      datetime: this.getdate(this.data.date),
      dateshow: false
    })
  },
  //出发时间变化按钮
  onChangedate(event) {
    this.setData({
      date: event.detail
    })
  },
  getdate(givenTimestamp) {
    // 创建一个Date对象
    const date = new Date(givenTimestamp); // 将秒转换为毫秒

    // 格式化日期
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');

    // 组合成YYYY/MM/DD格式的字符串
    return `${year}/${month}/${day}`;

  },
  //人物改变
  onpersonChange(e) {
    this.setData({
      person: e.detail
    })
  },

  //消费变化
  moneychange(e) {
    console.log(e);
    this.setData({
      money: e.detail.value
    })
  },

  onnumChange(e) {
    this.setData({
      num: e.detail
    });
  },

  nextstep() {
    let that = this
    const nextdata = {
      id:writestore.writestrategy.id ? writestore.writestrategy.id :'',
      title: writestore.writestrategy.title,
      date: this.data.datetime,
      people: this.data.person,
      money: this.data.money,
      tag:JSON.stringify(this.data.taglist),
      content: writestore.writestrategy.content,
      num: this.data.num,
      img: writestore.writestrategy.bgimg,
      author: JSON.parse(wx.getStorageSync('userinfo')).username
    }
  
    if (!this.data.datetime || !this.data.money || !this.data.person||!this.data.taglist.length) {
      Toast('请完善信息后再发布哦~')
      return
    }
    let url='/strategy/write'
    if(writestore.writestrategy.id){
      url='/strategy/update'
    }
    myRequest.post(url, nextdata).then(res => {
      wx.showToast({
        title: '发布成功！',
        icon: 'success',
        duration: 1000
      })
      writestore.updatewritestrategy({})
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }, 1000);
    })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})